#!/usr/bin/env python3
import sys
import copy

matrix = []
for line in sys.stdin:
    matrix.append([ int(e) for e in line.rstrip('\n') ])
matrix_next = copy.deepcopy(matrix)
flashed = [[ False for e in row ] for row in matrix ]
flashes = 0
prev_flashes = 0

for i in range(int(sys.argv[1]) + 1 if len(sys.argv) > 1 else 128):
    prev_flashes = flashes
    for run in range(8):
        for y in range(len(matrix)):
            for x in range(len(matrix[y])):
                if run == 0:
                    matrix_next[y][x] += 1
                if matrix_next[y][x] > 9 and not flashed[y][x]:
                    flashes += 1
                    flashed[y][x] = True
                    for y_offset in range(-1, 2):
                        if y + y_offset < 0 or y + y_offset >= len(matrix): continue
                        for x_offset in range(-1, 2):
                            if x + x_offset < 0 or x + x_offset >= len(matrix[y]): continue
                            matrix_next[y + y_offset][x + x_offset] += 1
    for y, row in enumerate(matrix):
        for x, col in enumerate(row):
            if flashed[y][x]:
                matrix_next[y][x] = 0
                flashed[y][x] = False
    print('matrix')
    print('\n'.join(', '.join([ '\033[95m' + str(e) + '\033[0m' if e == 0 else str(e) for e in row ]) for row in matrix))
    #print('next')
    #print('\n'.join(', '.join([ '\033[95m' + str(e) + '\033[0m' if e == 0 else str(e) for e in row ]) for row in matrix_next))
    print('\n'.join(str(row) for row in flashed))
    print(f'total of {prev_flashes} after {i} steps')
    matrix = copy.deepcopy(matrix_next)